// @ts-nocheck
import { useState, useEffect } from "react";
import { translateTreeToList } from '@/utils/translate'

export const useMenuProps = (menu, history) => {
  const [menuProps, setMenuProps] = useState(menu);

  const handleSkip = (menu) => {
    if (menu?.children?.length > 0) {
      const child = menu.children.find(
        (item) => item.id == menu.active
      );
      if (child?.path) {
        localStorage.setItem('menuProps', JSON.stringify(menuProps))
        if (child.path.startsWith('/edr') && !sessionStorage.getItem('skipPath')?.startsWith('/edr')) {
          window.location.href = `${window.location.origin}${child.path}`
        } else {
          history.push(child.path)
        }
        sessionStorage.setItem('skipPath', child.path)
      } else {
        handleSkip(child);
      }
    }
  };

  const handleMenuClick = (pid, id) =>
    setMenuProps((menu) => {
      let flag = false; // 是否更改
      const handleActive = (menu, pid, id) => {
        if (menu.id == pid) {
          if (menu.active != id) {
            flag = true;
            menu.active = id;
            handleSkip(menu);
          }
        } else {
          menu.children?.forEach((item) => handleActive(item, pid, id));
        }
      };
      handleActive(menu, pid, id);
      return flag ? { ...menu } : menu;
    });
  
  const getActiveMenu = (menu, pathname) => {
    const menuList = translateTreeToList(menu.children, menu.id)
    const lastMenu = menuList.find(item => item?.path == pathname)
    if (lastMenu) {
      const { pid, id } = lastMenu
      const parent = menuList.find(item => item.id == pid)
      const activeIds = [id, pid, parent.pid]
      const handleActive = (menu/* , activeIds */) => {
        if (menu && activeIds.length > 0) {
          const activeId = activeIds.pop()
          menu.active = activeId
          if (menu?.children) {
            const childMenu = menu.children.find(item => item.id == activeId)
            handleActive(childMenu/* , activeIds */)
          }
        }
      }
      handleActive(menu)
      return { ...menu }
    } else {
      return JSON.parse(localStorage.getItem('menuProps'))
    }
  }

  useEffect(() => {
    localStorage.setItem('menuProps', JSON.stringify(menuProps))
  }, [])

  useEffect(() => {
    setMenuProps(menuProps => getActiveMenu(menuProps, history.location.pathname))
  }, [history.location.pathname])

  return [menuProps, handleMenuClick];
};
